package com.wlps.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wlps.contant.Contant;
import com.wlps.entity.ReturnOutOfStock;
import com.wlps.entity.Supplier;
import com.wlps.mapper.SupplierMapper;
import com.wlps.result.ResultPageVo;
import com.wlps.result.ResultUtils;
import com.wlps.result.ResultVo;
import com.wlps.service.ISupplierService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wlps.vo.sendcenter.supplier.SupplierAddVo;
import com.wlps.vo.sendcenter.supplier.SupplierUpdateVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 供应商表(supplier) (没有使用复合索引数据量大时可能回表操作很影响性能) 服务实现类
 * </p>
 *
 * @author ZWYZY
 * @since 2020-07-31
 */
@Service
@Slf4j
public class SupplierServiceImpl extends ServiceImpl<SupplierMapper, Supplier> implements ISupplierService, InitializingBean {


    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public void afterPropertiesSet() throws Exception {
        initSupplier();
    }

    /**
     * 初始化缓存
     */
    void initSupplier() {
        List<Supplier> supplierList;
        if (redisTemplate.hasKey(Contant.SUPPLIERS_KEY)) {
            supplierList = (List<Supplier>) redisTemplate.opsForValue().get(Contant.SUPPLIERS_KEY);
        } else {
            supplierList = baseMapper.selectList(null);
            redisTemplate.opsForValue().set(Contant.SUPPLIERS_KEY, supplierList,5, TimeUnit.MINUTES);
            log.info("初始化所有供应商-------存入缓存数据");
        }
        if (!redisTemplate.hasKey(Contant.SUPPLIERLIST_KEY)) {
            redisTemplate.opsForList().rightPushAll(Contant.SUPPLIERLIST_KEY, supplierList);
            redisTemplate.expire(Contant.SUPPLIERLIST_KEY,5,TimeUnit.MINUTES);
            log.info("初始化供应商列表--------存入缓存数据");
        }
    }

    @Override
    public ResultPageVo<List<Supplier>> getSupplier(int pageNum, int pageSize, String name) {
        initSupplier();
        //总条数
        long count;
        List<Supplier> supplierList;

        if (name == null) {
            //不是条件查询，redis
            count = (Long) redisTemplate.opsForList().size(Contant.SUPPLIERLIST_KEY);
            //当前页从第几条开始查
            long fromNum = pageSize * (pageNum - 1);
            if (fromNum >= count) {
                supplierList = (List<Supplier>) redisTemplate.opsForList().range(Contant.SUPPLIERLIST_KEY, 0, count);
            } else {
                //当前页最后第几条
                long toNum = fromNum + pageSize >= count ? count : fromNum + pageSize;
                supplierList = (List<Supplier>) redisTemplate.opsForList().range(Contant.SUPPLIERLIST_KEY, fromNum, toNum-1);
            }

//            RedisConfig.returnJedis(jedis);

        } else {//条件查询，mysql
            Page<Supplier> supplierPage = new Page<>(pageNum, pageSize);
            LambdaQueryWrapper<Supplier> queryWrapper = new QueryWrapper<Supplier>().lambda().eq(Supplier::getSupplierName, name);
            IPage<Supplier> page = this.baseMapper.selectPage(supplierPage, queryWrapper);
            supplierList = page.getRecords();
            count = page.getSize();
        }

        //分页返回值封装
        ResultPageVo resultPageVo = new ResultPageVo("响应成功", 200, (long) pageSize, (long) pageNum, count, supplierList);

        return resultPageVo;
    }

    @Override
    public ResultVo deleteSupplier(Long id) {
        if (((List<Supplier>) redisTemplate.opsForValue().get(Contant.SUPPLIERS_KEY)).stream().filter(x -> x != null && id.equals(x.getId())).count() == 0) {
            return ResultUtils.error("供应商编号查询不到，请输入正确的供应商编号，亲", 30000);
        }
        baseMapper.deleteById(id);
        supplierUpdateCache();
        return ResultUtils.success("移除供应商成功，亲");
    }

    @Override
    public ResultVo updateSupplier(SupplierUpdateVo supplierUpdateVo) {
        if (((List<Supplier>) redisTemplate.opsForValue().get(Contant.SUPPLIERS_KEY)).stream().filter(x -> x != null && supplierUpdateVo.getSupplierName().equals(x.getSupplierName()) && !supplierUpdateVo.getId().equals(x.getId())).count() != 0) {
            return ResultUtils.error("系统有同名供应商，请换个供应商名称试试，亲", 30001);
        }
        if (((List<Supplier>) redisTemplate.opsForValue().get(Contant.SUPPLIERS_KEY)).stream().filter(x -> x != null && supplierUpdateVo.getBankNumber().equals(x.getBankNumber()) && !supplierUpdateVo.getId().equals(x.getId())).count() != 0) {
            return ResultUtils.error("系统有同名银行卡号，请换个银行卡号试试，亲", 30002);
        }
        if (((List<Supplier>) redisTemplate.opsForValue().get(Contant.SUPPLIERS_KEY)).stream().filter(x -> x != null && supplierUpdateVo.getPhone().equals(x.getPhone()) && !supplierUpdateVo.getId().equals(x.getId())).count() != 0) {
            return ResultUtils.error("系统有同名电话号码，请换个电话号码试试，亲", 30003);
        }
        Supplier supplier = new Supplier();
        BeanUtils.copyProperties(supplierUpdateVo, supplier);
        baseMapper.updateById(supplier);
        supplierUpdateCache();
        return ResultUtils.success("修改供应商信息成功，亲");
    }

    @Override
    public ResultVo addSupplier(SupplierAddVo supplierAddVo) {
        if (((List<Supplier>) redisTemplate.opsForValue().get(Contant.SUPPLIERS_KEY)).stream().filter(x -> x != null && supplierAddVo.getSupplierName().equals(x.getSupplierName())).count() != 0) {
            return ResultUtils.error("系统有同名供应商，请换个供应商名称试试，亲", 30001);
        }
        if (((List<Supplier>) redisTemplate.opsForValue().get(Contant.SUPPLIERS_KEY)).stream().filter(x -> x != null && supplierAddVo.getBankNumber().equals(x.getBankNumber())).count() != 0) {
            return ResultUtils.error("系统有同名银行卡号，请换个银行卡号试试，亲", 30002);
        }
        if (((List<Supplier>) redisTemplate.opsForValue().get(Contant.SUPPLIERS_KEY)).stream().filter(x -> x != null && supplierAddVo.getPhone().equals(x.getPhone())).count() != 0) {
            return ResultUtils.error("系统有同名电话号码，请换个电话号码试试，亲", 30003);
        }
        Supplier supplier = new Supplier();
        BeanUtils.copyProperties(supplierAddVo, supplier);
        baseMapper.insert(supplier);
        supplierUpdateCache();
        return ResultUtils.success("新录入供应商信息成功，亲");
    }

    @Override
    public ResultVo<Supplier> getSupplierById(Long id) {
        if (((List<Supplier>) redisTemplate.opsForValue().get(Contant.SUPPLIERS_KEY)).stream().filter(x -> x != null && id.equals(x.getId())).count() == 0) {
            return ResultUtils.error("供应商编号查询不到，请输入正确的供应商编号，亲", 30000);
        }
        Supplier supplier = baseMapper.selectById(id);
        return ResultUtils.success("查询成功，亲", supplier);
    }


    /**
     * 更新缓存
     */
    @Async
    public void supplierUpdateCache() {
        List<Supplier> supplierList = baseMapper.selectList(null);
        redisTemplate.opsForValue().set(Contant.SUPPLIERS_KEY, supplierList,5,TimeUnit.MINUTES);
        redisTemplate.delete(Contant.SUPPLIERLIST_KEY);
        redisTemplate.opsForList().rightPushAll(Contant.SUPPLIERLIST_KEY, supplierList);
        redisTemplate.expire(Contant.SUPPLIERLIST_KEY,5,TimeUnit.MINUTES);
        log.info("所有供应商-------更新缓存数据");
    }
}
